/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ChateoNI;

import java.net.*;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

/**
 *
 * @author abdala
 */
public class ConnexionUDPServer extends Thread {
    private DatagramSocket socketServ;
    private final int DATA_SIZE=1000;
    private final int portServ=2014;

    public ConnexionUDPServer() throws SocketException{
        //Create a UDP socket linked to the server's port
        socketServ = new DatagramSocket(portServ);  
        //Starting the reception Thread
        super.start();
    }
    
    public void run() {
        boolean active=true;
        while(active){
            try{
                //An array for data reception
                byte[] data = new byte[DATA_SIZE];
                
                //Creation of a packet using the data array
                DatagramPacket packet = new DatagramPacket(data, data.length);
                
                
                //Waiting for a packet
                socketServ.receive(packet);
                
                //Getting IP Adress of the current client
                InetAddress ClientIP = packet.getAddress();
                
                
                //Displaying data received
                //String car = new String(packet.getData(),0,packet.getLength());
                Message msg = Message.fromArray(data);
                
                if(msg instanceof Hello) {
                    
                    Hello hello = (Hello)msg;
                     hello.getlogin();
                }
                else if (msg instanceof Bye) {
                    Bye bye = (Bye)msg;
                    bye.getLogin();
                    
                }
                else {
                //WHAT IS THIS MESSAGE ?!
                    System.out.println("ERROR : What is this message ?");
                }
                
                System.out.println("The server has received : " +msg.toString());
            }
            catch(Exception e){
                active = false;
                e.printStackTrace();
            }
        }
        
    }
    
    // pour les tests
    public static void main(String[] args) throws Exception {
        ConnexionUDPServer server=new ConnexionUDPServer();
        server.run();
    }
    
    
    
}